<?php
namespace app\cls\OAuth2;
abstract class BaseThirdLogin{
	protected $app_key = "";//appid
	protected $app_secret = "";//app秘钥

	public function __construct(array $config=[])
	{
		self::config($this,$config);
	}
	public function __set($name,$value)
	{
		$method = "set".ucfirst($name);
		if(method_exists($this,$method)){
			$this->$method($value);
		}else{
			throw new AuthException("不能设置属性{$name}");
		}
	}
	public function __get($name)
	{
		return $this->$name;
	}
	public function setApp_key($value)
	{
		 $this->app_key = $value;
	}
	public function setApp_secret($value)
	{
		$this->app_secret = $value;
	}
	public static function config($obj,array $config)
	{
		foreach($config as $key=>$value){
			$obj->$key = $value;
		}
	}
	abstract public function getAccessToken(array $params=[]);
	abstract public function getUserInfo(array $params=[]);
	abstract public function refreshAccessToken(array $params=[]);
    //http请求
    public function curl($url,$data=[],$type="post",$https=false,$header="")
    {
        $ch = curl_init();//curl句柄
        curl_setopt($ch,CURLOPT_TIMEOUT,10);//5秒的超时时间
        if($type == "get"){
            $url = $url."?".http_build_query($data);
        }
        if($header){
            curl_setopt($ch,CURLOPT_HTTPHEADER ,$header);
        }
        curl_setopt($ch,CURLOPT_URL ,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER ,1);
        if($type == "post"){
            curl_setopt($ch,CURLOPT_POST,1);
            $data = http_build_query($data);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        if($https==true){
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
        }else{
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        }
        $result =  curl_exec($ch);
        if($result){
            curl_close($ch);
            return $result;
        }else{
            $error = curl_error($ch);
            curl_close($ch);
            throw new AuthException("curl错误:".$error);
        }
    }
} 